package Huffman;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Description:
 * Author:    Dane
 * CreateTime:2024/8/24-下午2:35
 * Since  :   1.0
 * Version:   1.0
 */
public class HuffmanTree {
    public void midOrder(Node root) {
        if (root != null) {
            root.midOrder();
        } else {
            System.out.println("the root node is null");
        }
    }

    public Node createHuffmanTree(int[] arr) {
        List<Node> nodes = new ArrayList<>();
        for (int i : arr) {
            nodes.add(new Node(i));
        }

        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);

            Node parent = new Node(leftNode.value + rightNode.value);
            parent.leftNode = leftNode;
            parent.rightNode = rightNode;

            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);


        }
        return  nodes.get(0);

    }

    public static void main(String[] args) {
        HuffmanTree huffmanTree = new HuffmanTree();
        int []arr={13,7,8,3,29,6,1};
        Node root = huffmanTree.createHuffmanTree(arr);
      huffmanTree.midOrder(root);
    }


}
